package com.ruoyi.pdf;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.annotation.PostConstruct;

@Service
public class PdfGenerateServiceImpl implements PdfGenerateService {
    private Logger logger = LoggerFactory.getLogger(PdfGenerateServiceImpl.class);

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${ruoyi.profile}")
    private String profilePath;
    private String pdfDirectory;
    
    
    @PostConstruct
    public void init(){
    	pdfDirectory = profilePath + "/pdf/";
    	File directory = new File(pdfDirectory);
    	if(!directory.exists()){
    		directory.mkdirs();
    	}
    }
    @Override
    public void generatePdfFile(String templateName, Map<String, Object> data, String pdfFileName) {
        Context context = new Context();
        context.setVariables(data);
        
        String htmlContent = templateEngine.process(templateName, context);
        try {
        	File pdfFile = new File(pdfDirectory + pdfFileName);
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            try {
            	
            	//String path = ResourceUtils.getFile("classpath:pdf-templates/simsun.ttf").getPath();;
            	String	path = ResourceUtils.getFile(profilePath+"/simsun.ttf").getPath();
				fontResolver.addFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			} catch (IOException e) {
				e.printStackTrace();
			}
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            renderer.createPDF(fileOutputStream, false);
            renderer.finishPDF();
            generateWaterMark(pdfFile);
			
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (DocumentException e) {
            logger.error(e.getMessage(), e);
        }
    }
    
    private  File paint(File file) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(file.getPath());
        File dest = File.createTempFile("withMask", "pdf", file);
      
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

        int n = reader.getNumberOfPages();
        stamper.setRotateContents(false);
        String	path = ResourceUtils.getFile(profilePath+"/simsun.ttf").getPath();
        BaseFont chinese = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        // text watermark
        Font f = new Font(chinese, 20);
        // transparency
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.1f);

        // properties
        PdfContentByte over;
        Rectangle pagesize;
        float x, y;
        // loop over every page
        for (int i = 1; i <= n; i++) {
            pagesize = reader.getPageSize(i);

            over = stamper.getOverContent(i);
            over.saveState();
            over.setGState(gs1);

            x = (pagesize.getLeft() + pagesize.getRight()) / 2 - 25;
            y = (pagesize.getTop() + pagesize.getBottom()) / 2 + 60;

            Phrase p = new Phrase("实验室建设与管理处", f);
            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 45);

            over.restoreState();
        }
        stamper.close();
        reader.close();
        return dest;
    }
    
    public void generateWaterMark(File target) {
        try {
            PdfReader pdfReader = new PdfReader(new FileInputStream(target));
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(target));
            // 原pdf文件的总页数
            int pageSize = pdfReader.getNumberOfPages();
            // 设置字体
            BaseFont font = BaseFont.createFont(profilePath+"/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // 设置填充字体不透明度为0.2f
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);
            Document document = new Document();
            float documentWidth = document.getPageSize().getWidth(), documentHeight = document.getPageSize().getHeight();
            final float xStart = 0, yStart = 0, xInterval = 80, yInterval = 80, rotation = 30, fontSize = 16;
            String watermarkWord = "实验室建设与管理处";
            int red = 128, green = 128, blue = 128;

            for (int i = 1; i <= pageSize; i++) {
                // 水印在之前文本下
                PdfContentByte pdfContentByte = pdfStamper.getUnderContent(i);
                pdfContentByte.beginText();
                // 文字水印 颜色
                pdfContentByte.setColorFill(new Color(red, green, blue));
                // 文字水印 字体及字号
                pdfContentByte.setFontAndSize(font, fontSize);
                pdfContentByte.setGState(gs);
                // 文字水印 起始位置
                pdfContentByte.setTextMatrix(xStart, yStart);

                for (float x = xStart; x <= documentWidth + xInterval; x += xInterval) {
                    for (float y = yStart; y <= documentHeight + yInterval; y += yInterval) {
                        pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkWord, x, y, rotation);
                    }
                }
                pdfContentByte.endText();
            }
            // 关闭
            pdfStamper.close();
            pdfReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
